<template>
  <el-dialog
    append-to-body
    :title="info+'-商品'"
    :visible.sync="dialogVisible"
    align="left"
    v-loading="currLoading"
    :close-on-click-modal="false"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    top="20px"
    width="1700px">
    <el-form v-if="dialogVisible" ref="form" :model="form" label-width="150px" :rules="rules">
      <el-form-item label="主图" align="left" prop="image">
        <el-upload
          class="avatar-uploader"
          :action="UploadFileUrl"
          :headers="getHeader()"
          name="myUploadFile"
          :show-file-list="false"
          :on-success="uploadIconSuccess">
          <img v-if="form.image" :src="form.image" class="avatar" style="width: 100px">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-input readonly v-model="form.image" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="多图" align="left" prop="imageArr">
        <my-upload-more ref="my-upload-more" :image-params-arr="form.imageArr" :callback="callbackSetImageArr"/>
      </el-form-item>
      <el-form-item label="名称" align="left" prop="name">
        <el-input v-model.trim="form.name" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="热门标签" align="left" prop="hotTag">
        <el-tag
          size="medium"
          effect="dark"
          type="warning"
          :key="index"
          v-for="(tag,index) in hotTagArr"
          closable
          style="margin-left: 5px"
          :disable-transitions="false"
          @close="handleClose(index)">
          {{tag}}
        </el-tag>
        <el-button type="primary" @click="newTag">新增-热门标签</el-button>
      </el-form-item>
      <el-form-item label="品牌" align="left">
        <shop-brand-box ref="shop-brand-box" :set-call-back="setBrand" :init-brand="form.brandId?form.brandId:0"/>
      </el-form-item>
      <el-form-item label="分类" align="left" prop="classifyId">
        <shop-classify-box :set-call-back="setClassifyId" :init-classify-id="form.classifyId"/>
      </el-form-item>
      <el-form-item label="规格" align="left" prop="specifications">
        <product-specifications-select-box ref="product-specifications-select-box" :callback="setSpecifications"/>
      </el-form-item>
      <el-form-item label="型号" align="left" prop="modelArr">
        <product-model-box ref="product-model-box" :init-curr-list="form.modelArr" :call-back="setModelArr"/>
      </el-form-item>
      <el-form-item label="描述" align="left" prop="content">
        <my-editor ref="my-editor" :call-back="editorSetContent" :content-params="form.content"/>
      </el-form-item>
    </el-form>
    <div align="center">
      <el-button type="primary" @click="submit">提 交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import ProductModelBox from './ProductModelBox'
import ProductSpecificationsBox from './ProductSpecificationsBox'
import MyEditor from '../Common/MyEditor'
import MyUploadMore from '../Common/MyUploadMore'
import ShopBrandBox from '../Common/ShopBrandBox'
import ShopClassifyBox from '../Common/ShopClassifyBox'
import ProductSpecificationsSelectBox from '../Common/ProductSpecificationsSelectBox'

export default {
  name: 'CreateProductDialog',
  components: {
    ProductSpecificationsSelectBox,
    ShopClassifyBox,
    ShopBrandBox,
    MyUploadMore,
    MyEditor,
    ProductSpecificationsBox, ProductModelBox
  },
  props: {
    successFunction: Function
  },
  data: function () {
    return {
      defaultClassifyName: [],
      classifyNameOptions: [],
      info: '',
      dialogVisible: false,
      currLoading: false,
      statusArr: AllConst.StatusArr,
      hotTagArr:[],
      form: {
        id: 0,
        name: '',
        hotTag: '',
        classifyId: 0,
        brandId: 0,
        price: 0,
        image: '',
        modelArr: [],
        defaultModelNums: 100,
        specificationsArr:[],
        imageArr: [],
        status: '1',
        content: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入 名称', trigger: ['blur', 'change']},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: ['blur', 'change']}
        ],
        brandId: [
          {required: false, message: '请输入 品牌', trigger: ['blur', 'change']},
        ],
        price: [
          {required: true, message: '请输入 价格', trigger: ['blur', 'change']},
        ],
        classifyId: [
          {required: true, message: '请选择 分类', trigger: ['blur', 'change']},
        ],
        image: [
          {required: true, message: '请上传 主图', trigger: ['blur', 'change']},
        ],
        imageArr: [
          {required: false, message: '请上传 多图', trigger: ['blur', 'change']},
        ],
        modelArr: [
          {required: true, message: '请填写 型号', trigger: ['blur', 'change']},
        ]
      }
    }
  },
  mounted () {

  },
  methods: {
    setModelArr:function (modelArr) {
      this.form.modelArr=modelArr
    },
    newTag:function () {
      let $this = this
      $this.$prompt('请输入 【热门标签】原因', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue:'',
        inputPattern: /^[\w\W]{1,15}$/,
        inputErrorMessage: '【热门标签】,长度在(1,15)位之间'
      }).then(({value}) => {
        if (value.length >100) {
          return $this.$message.warning('【热门标签】,必须在100个字符以内')
        }
        if ($this.hotTagArr.length>3){
          return $this.$message.warning('单个商品【热门标签】数量不能超过3个')
        }
        $this.hotTagArr.push(value)
      })
    },
    handleClose:function (index) {
      this.hotTagArr.splice(index)
      this.$forceUpdate()
    },
    setSpecifications:function (specificationsArr) {
      // console.log('specificationsArr',specificationsArr)
      this.form.specificationsArr=specificationsArr
      this.$refs['product-model-box'].setProductSpecifications(specificationsArr)
    },
    // 设置分类ID
    setClassifyId:function (classifyId) {
      this.form.classifyId=classifyId-0
    },
    // 设置品牌
    setBrand:function (brandId) {
      this.form.brandId=brandId
    },
    // 打开弹窗
    open: function (info) {
      let $this = this
      $this.hotTagArr=[]
      $this.info = '创建'
      // console.log('$this.shopProductClassifyNameArr',$this.shopProductClassifyNameArr)
      if (info && info.id > 0) {
        $this.info = '更新'
        this.form.id=info.id
        this.getDetail()
      } else {
        $this.form = {
          id: 0,
          name: '',
          hotTag: '',
          brandId: '',
          classifyId: 0,
          price: 0,
          image: '',
          imageArr: [],
          modelArr: [],
          specificationsArr: [],
          content: ''
        }
        if ($this.$refs.form) {
          $this.$refs.form.resetFields()
        }
        $this.dialogVisible = true
      }
      if (process.env.NODE_ENV === 'development') {
        // this.setDemo()
      }
      $this.$forceUpdate()
    },
    getDetail:function () {
      let $this=this
      $this.MyRequest(this.ApiDoNameShop + 'Product/getProductDetail', {id:$this.form.id}, function (res) {
        // console.log('res',res)
        $this.form.name=res.shopProduct.name
        $this.form.hotTag=res.shopProduct.hotTag
        if ($this.form.hotTag){
          $this.hotTagArr=$this.form.hotTag.split(',')
          $this.form.hotTag=$this.hotTagArr.join(',')
        }else{
          $this.hotTagArr=[]
          $this.form.hotTag=''
        }
        $this.form.brandId=res.shopProduct.brandId
        $this.form.classifyId=res.shopProduct.classifyId
        $this.form.image=res.shopProduct.image
        $this.form.imageArr=JSON.parse(res.shopProduct.imageArr)
        $this.form.content=res.shopProduct.content

        $this.form.modelArr=res.shopProductStockList
        $this.form.specificationsArr=JSON.parse(res.shopProduct.specificationsArr)
        setTimeout(function () {
          $this.$refs['product-model-box'].setProductSpecifications($this.form.specificationsArr)
          $this.$refs['product-specifications-select-box'].setSelectIds($this.form.specificationsArr)
        },500)
        $this.dialogVisible = true
        $this.$forceUpdate()
      }, function (response) {
        $this.$message.success(response.message)
        $this.currLoading = false
        $this.$forceUpdate()
      })
    },
    setDemo: function () {
    },
    editorSetContent: function (content) {
      this.form.content = content
    },
    uploadIconSuccess: function (res) {
      this.form.image = res.data
    },
    callbackSetImageArr:function (imageArr) {
      // console.log('imageArr',imageArr)
      this.form.imageArr=imageArr
    },
    submit: function () {
      let $this = this
      var errorInfo = $this.$refs['product-model-box'].getErrorInfo()
      if (errorInfo.length>0){
        return this.$message.error('型号数据 输入错误')
      }
      if ($this.$refs['product-model-box'].getCurrList().length===0){
        return this.$message.error('型号数据 不能为空')
      }
      if (this.form.classifyId===0){
        return this.$message.error('分类数据 不能为空')
      }
      $this.$refs.form.validate((valid) => {
        if (valid) {
          var api = 'Product/createProductAndModel'
          var form = Object.assign({}, $this.form)
          if (this.form.id > 0) {
            api = 'Product/updateProductAndModel'
          }
          if ($this.form.imageArr.length > 0) {
            form.imageArr = $this.form.imageArr.join(',')
          } else {
            delete form.imageArr
          }
          if (!form.brandName){
            delete form.brandName
          }
          if (form.content.length>50000){
            return $this.$message.error('商品描述 必须在50000个字符以内')
          }
          if (!form.content){
            delete form.content
          }
          var modelArr=$this.$refs['product-model-box'].getCurrList()
          form.modelArr=JSON.stringify(modelArr)
          if ($this.hotTagArr.length>0){
            form.hotTag=$this.hotTagArr.join(',')
          }
          form.specificationsArr=JSON.stringify(form.specificationsArr)
          $this.MyRequest(this.ApiDoNameShop + api, form, function () {
            $this.$message.success($this.info + '成功')
            // $this.currLoading = false
            if (typeof $this.$props.successFunction==='function'){
              $this.$props.successFunction()
            }
            $this.dialogVisible = false
            $this.$forceUpdate()
          }, function (response) {
            $this.$message.error(response.message)
            $this.currLoading = false
            $this.$forceUpdate()
          })
        } else {
          return false
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
